package Window;
//游戏结束时放音乐
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;

public class GameOver{
    public JFrame frame2 = new JFrame("over");
    private Clip clip;
    //要是胜利的话
    public void victory() {
        playAudio(1);//播放胜利的音乐
        Init();//初始化窗口
        ImageIcon imageIcon = new ImageIcon("src/Window/images/win.jpg");
        JLabel label = new JLabel();
        label.setIcon(imageIcon);
        frame2.add(label);
        frame2.setVisible(true);//这个还是要放到最后
    }
    public void fail() {
        playAudio(0);
        Init();
        frame2.setSize(550, 500);
        frame2.setLocationRelativeTo(null);
        ImageIcon imageIcon = new ImageIcon("src/Window/images/失败2.png");
        JLabel label = new JLabel();
        label.setIcon(imageIcon);
        frame2.add(label);
        frame2.setVisible(true);//这个还是要放到最后
    }
    public void Init() {
        frame2.setSize(280, 280);
        frame2.setLocation(400, 400);
        frame2.setLocationRelativeTo(null);
        frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
        frame2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                frame2.setVisible(false); // 关闭窗口
            }
        });

    }
    public void playAudio(int x) {
        try {
            // 加载音频文件
            File file;
            if(x == 1) {
                 file = new File("src/Window/musics/胜利.wav");
            } else {
                 file = new File("src/Window/musics/失败.wav");
            }
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);

            // 获取音频流信息
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            clip = (Clip) AudioSystem.getLine(info);

            // 打开音频流线路
            clip.open(audioStream);

            // 播放音频
            clip.start();

            // 关闭音频流
            try {
                audioStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
       //捕获可能发生的异常
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
